const systemInfo = wx.getSystemInfoSync();
const version = systemInfo.SDKVersion;
!function () {
  var PageTmp = Page;
  Page = function (pageConfig) {
    pageConfig = Object.assign({
      // onShareAppMessage: function () {
      //   return {
      //     title: '纤维肌痛康复训练平台',
      //     path: '/pages/navigation/index/index',
      //     imageUrl: 'https://7633-v3-92ah4-1300208657.tcb.qcloud.la/static/share_all.jpg',
      //   };
      // }
    }, pageConfig);
    PageTmp(pageConfig);
  };
}();

/*
 * 
 * 2021-08-31
 * 
 * 获取当前版本
 *
*/
const accountInfo = wx.getAccountInfoSync();
const envVersion = accountInfo.miniProgram.envVersion;
if (!envVersion) {
  console.error("获取运行环境失败!");
}

// "lazyCodeLoading": "requiredComponents",
const api = {
  // 开发版 - 环境  cb01-tlg8r
  develop: "cloud1-6glssxhfb29f99a2",
  // 体验版 - 环境
  trial: "cloud1-6glssxhfb29f99a2",
  // 正式版 - 环境 v3-92ah4
  release: "cloud1-6glssxhfb29f99a2"
};
// api[envVersion]
const ENV = api[envVersion]
console.log = envVersion !== 'develop' ? () => {} : console.log
App({
  data: {
    
  },
  globalData: {
    xCustomer: {
      phone_number:''
    },
    xRegister: [],
    is_Refresh:false,
    user:'',
    isinit:true,
    // 获取用户标签
    label:false,
    labelitem:{},
    lock:false,
    user_refresh:false,
    product_buy:false,
    scrollTop:false,
    InfoRefresh:false,
    needAuthorization:false,
    needCompleteEvaluation:false, // 是否需要完成h5测评
  },
  onShow:function(){
    let that = this
    wx.setStorageSync('task', [])
    that.globalData.lock = false
    this.needPrivacySetting()
    // 社区消息通知
    // wx.setTabBarBadge({
    //   index: 2,
    //   text: '3'
    // })
    // wx.removeTabBarBadge({
    //   index: 2,
    // })
    // that.xInnerAudio() //背景音频播放
  },
  onLaunch: function (options) {
    // this.globalData.tabbar =this.globalData.tabbarf
    if (!wx.cloud) {
      console.error('请使用 2.2.3 或以上的基础库以使用云能力')
    } else {
      wx.cloud.init({
        env: ENV,
        traceUser: true
      })
    }
    // 如果是扫码进入 第一次不校验是否选择疼痛类型
    if( options.scene !=1047 && options.scene !=1048 && options.scene !=1049  && options.scene !=1065 && options.scene !=1082 && options.scene !=1081 && options.scene !=1194 && options.scene !=1202  && options.scene!=1074 && options.scene!=1074){
      // 用户注册检查
      this.xReadyCheck()
    }
    // 是否扫码进入
    // if(JSON.stringify(options.query) !=="{}" ){
      this.xLogin(options.query)
    // }
    // 检查更新
    // this.updateCheck()
    // this.getlable()
    
    // 用户设备信息
    this.xSyetem()
    // this.authorizeLogin()

    // 场景值 1011 1012 1013
    // let scene = wx.getLaunchOptionsSync()
  },
  onHide:function(){
    this.globalData.is_Refresh = true
    wx.setStorageSync('is_official_account', false)
  },
  watch: function (ctx, obj) {
    Object.keys(obj).forEach(key => {
      this.observer(ctx.data, key, ctx.data[key], function (value) {
        obj[key].call(ctx, value)
      })
    })
  },
  // 获取用户购买状态
  // xInit:function(){
  //   let that= this
  //   wx.cloud.callFunction({
  //     name: 'digital_therapy',
  //     data: {
  //       action: "get_going_project"
  //     }
  //   }).then(res => {
  //     if(res.result.additional.buy_status !=0){
  //       that.globalData.product_buy = true
  //     }
  //   })
  // },
  
  // 获取设备信息
	xSyetem:function(){
    const screen_window=wx.getWindowInfo()
    const mobil_device_settings = wx.getSystemSetting()
    const deviceInfo = wx.getDeviceInfo()
    const appBaseInfo = wx.getAppBaseInfo()
    const accountInfo = wx.getAccountInfoSync()
    let _dataObj = {
        screen_window:screen_window,
        mobil_device_settings:mobil_device_settings,
        equipment_information:deviceInfo,
        app_base_info:appBaseInfo,
        current_account_information:accountInfo
    }
    wx.cloud.callFunction({
      name: 'clien_information_collection',
      data: {
        action: "save",
        dataObj: _dataObj
      }
    }).then(res => {})
},
  observer: function (data, key, val, fn) {
    Object.defineProperty(data, key, {
      configurable: true,
      enumerable: true,
      get: function () {
        return val
      },
      set: function (newVal) {
        if (newVal === val) return
        fn && fn(newVal)
        val = newVal
      },
    })
  },
  // 背景音频播放
  xInnerAudio:function(){
    const backgroundAudioManager = wx.getBackgroundAudioManager();
    // wx.setInnerAudioOption({
    //   mixWithOther:false //是否混播
    // })
    if (!backgroundAudioManager.src) {
      const innerAudioContext = wx.createInnerAudioContext()
      innerAudioContext.autoplay = true
      innerAudioContext.src = 'https://6362-cb01-tlg8r-1300208657.tcb.qcloud.la/cloudbase-cms/upload/2022-07-22/m63lzoctouisty3gke5tn09ksuoundvl_.m4a?sign=975c1314d400f41e881c40ce70ec0144&t=1658476076'
      innerAudioContext.onPlay(() => {
        console.log('开始播放')
      })
    }
    backgroundAudioManager.onStop(()=>{
      console.log('背景音频播放结束')
      const innerAudioContext = wx.createInnerAudioContext()
      innerAudioContext.autoplay = true
      innerAudioContext.src = 'https://6362-cb01-tlg8r-1300208657.tcb.qcloud.la/cloudbase-cms/upload/2022-07-22/m63lzoctouisty3gke5tn09ksuoundvl_.m4a?sign=975c1314d400f41e881c40ce70ec0144&t=1658476076'
      innerAudioContext.onPlay(() => {
        console.log('开始播放')
      })
    })
  },
  // 注册检查
  xReadyCheck: function () {
    let that =this
    wx.cloud.callFunction({
      name: 'user',
      data: {
        action: "detail"
      }
    }).then(res => {
      that.globalData.user = res.result;
      that.globalData.xCustomer = res.result;
      // if ( !res.result || JSON.stringify(res.result)==="{}" ) {
      //   wx.redirectTo({
      //     url: '/pages/navigation/label/index',
      //   })
      // }
    })
  },
  // updateCheck:function(){
  //   const updateManager = wx.getUpdateManager()
  //   updateManager.onCheckForUpdate(function (res) {
  //     // console.log(res.hasUpdate)
  //   })
  //   updateManager.onUpdateReady(function () {
  //     wx.showModal({
  //       title: '更新提示',
  //       content: '新版本已经准备好，是否重启应用?',
  //       success: function (res) {
  //         if (res.confirm) {
  //           updateManager.applyUpdate()
  //         }
  //       }
  //     })
  //   })
  // },
  xLogin:function(data){
    let that = this
    wx.cloud.callFunction({
      name: "user",
      data: {
        action: "login",
        userInfo: data,
      },
      success: function (res) {
        that.globalData.user = res.result;
        that.globalData.xCustomer = res.result;
      }
    })
  },
  authorizeLogin: function (e, success, fail, fail_show, extraData) {
    console.log(e, success, fail, fail_show, extraData)
    if (fail_show == undefined) { fail_show = true; }
    let _this = this;
    wx.getUserProfile({
      desc: '用于完善会员资料',
      fail: (res) => {
        if (fail_show) {
          _this.globalData.doctor_id = "ozJU44-tiWO-mgmzWSM_-uNIdCzU"
          wx.reLaunch({
            url: '/pages/navigation/index/index',
          })
        } else {
          fail && fail();
        }
      },
      success: (res) => {
        wx.showLoading({ title: "正在登录", mask: true });
        wx.cloud.callFunction({
          name: "user",
          data: {
            action: "login",
            userInfo: res.userInfo,//用户昵称 头像
            extraData: extraData //
          },
          success: function (res) {
            console.log(res)
            wx.hideLoading();
            if (res.result.success == false) {
              wx.showModal({
                title: '登录失败',
              })
              return false;
            }
            _this.globalData.user = res.result;
            _this.globalData.xCustomer = res.result;
            success && success(res);
          }
        })
      }
    })
  },
  // 是否最后一个任务完成
  xTodayLast:function(){
    let that = this
    // let date = new Date();
    // let dateDate = date.getFullYear() + '' +( Number(date.getMonth()) + 1) +'' +  date.getDate();
    // let value = wx.getStorageSync('dateKey')
    // wx.cloud.callFunction({
    //   name: 'digital_therapy_extend',
    //   data: {
    //      action:"is_completionStauts_by_today"
    //   }
    // }).then(res => {
    //   if(res.result && value != dateDate){
    //     wx.showModal({
    //       title: '恭喜您,今日打卡成功',
    //       content: '离100%退费又进一步~',
    //       showCancel:false,
    //       confirmText:'我知道了',
    //       complete: (res) => {
    //         if (res.confirm) {
    //           wx.setStorageSync('dateKey', dateDate)
    //         }
    //       }
    //     })
    //   }
    // }) 
  },
  // 检查是否需要同意隐私协议

  needPrivacySetting:function(){
    const version = wx.getAppBaseInfo().SDKVersion
    if (this.compareVersion(version, '2.32.3') >= 0) {
      wx.getPrivacySetting({
        success: res => {
          if (res.needAuthorization) {
            this.globalData.needAuthorization = true
            return true
          } else {
            this.globalData.needAuthorization = false
            return false
          }
        }
      })
    }
  },
  // 版本号比较
  compareVersion:function(v1, v2) {
    v1 = v1.split('.')
    v2 = v2.split('.')
    const len = Math.max(v1.length, v2.length)
  
    while (v1.length < len) {
      v1.push('0')
    }
    while (v2.length < len) {
      v2.push('0')
    }
  
    for (let i = 0; i < len; i++) {
      const num1 = parseInt(v1[i])
      const num2 = parseInt(v2[i])
  
      if (num1 > num2) {
        return 1
      } else if (num1 < num2) {
        return -1
      }
    }
  
    return 0
  }
  
});
